Chapter 25. Boost.PropertyTree

您所在的位置:网站首页 boost key Chapter 25. Boost.PropertyTree

Chapter 25. Boost.PropertyTree

2023-02-27 12:44| 来源: 网络整理| 查看: 265

Chapter 25. Boost.PropertyTree

With the class boost::property_tree::ptree, Boost.PropertyTree provides a tree structure to store key/value pairs. Tree structure means that a trunk exists with numerous branches that have numerous twigs. A file system is a good example of a tree structure. File systems have a root directory with subdirectories that themselves can have subdirectories and so on.

To use boost::property_tree::ptree, include the header file boost/property_tree/ptree.hpp. This is a master header file, so no other header files need to be included for Boost.PropertyTree.

Example 25.1. Accessing data in boost::property_tree::ptree#include #include using boost::property_tree::ptree; int main() { ptree pt; pt.put("C:.Windows.System", "20 files"); ptree &c = pt.get_child("C:"); ptree &windows = c.get_child("Windows"); ptree &system = windows.get_child("System"); std::cout Example 25.2 iterates over the subdirectories of C:\Windows. You can’t get an iterator to iterate over all branches in all levels.

The for loop in Example 25.2 reads the number of files in all subdirectories of C:\Windows to calculate a total. As a result, the example displays 70. The example doesn’t access objects of type ptree directly. Instead it iterates over elements of type std::pair. first contains the key of the current branch. That is System and Cursors in Example 25.2. second provides access to an object of type ptree, which represents the possible subdirectories. In the example, only the values assigned to System and Cursors are read. As in Example 25.1, the member function get_value() is called.

boost::property_tree::ptree only stores the value of the current branch, not its key. You can get the value with get_value(), but there is no member function to get the key. The key is stored in boost::property_tree::ptree one level up. This also explains why the for loop iterates over elements of type std::pair.

Example 25.3. Accessing data with a translator#include #include #include #include struct string_to_int_translator { typedef std::string internal_type; typedef int external_type; boost::optional get_value(const std::string &s) { char *c; long l = std::strtol(s.c_str(), &c, 10); return boost::make_optional(c != s.c_str(), static_cast(l)); } }; int main() { typedef boost::property_tree::iptree ptree; ptree pt; pt.put(ptree::path_type{"C:\\Windows\\System", '\\'}, "20 files"); pt.put(ptree::path_type{"C:\\Windows\\Cursors", '\\'}, "50 files"); string_to_int_translator tr; int files = pt.get(ptree::path_type{"c:\\windows\\system", '\\'}, tr) + pt.get(ptree::path_type{"c:\\windows\\cursors", '\\'}, tr); std::cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3